from operator import or_
from flask import (Blueprint, flash, render_template, g, request, redirect,
                   url_for)
from decorators import login_required
from models import QuestionPublicModel, AnswerQuestionModel
from .forms import QuestionPublicForm, AnswerQuestionForm
from exts import db
from sqlalchemy import or_

bp = Blueprint('qa', __name__, url_prefix='/')


@bp.route('/')
def index():
    # order_by(db.text('-create_time')根据时间倒叙展示
    questions = QuestionPublicModel.query.order_by(
        db.text('-create_time')).all()
    return render_template('index.html', questions=questions)


@bp.route('/question/public', methods=['GET', 'POST'])
@login_required  # 装饰器，做登录验证。
def question_public():
    if request.method == 'GET':
        return render_template('question_public.html')
    else:
        form = QuestionPublicForm(request.form)
        if form.validate():
            # save db
            title = request.form.get('title')
            content = request.form.get('content')
            model = QuestionPublicModel(title=title, content=content)
            user = g.get('user')
            model.author = user
            db.session.add(model)
            db.session.commit()

            return redirect('/')
        else:
            flash('请输入正确的标题和内容')
            return render_template('question_public.html')


@bp.route('question/public/detail/<int:id>')
@login_required
def question_detail(id):
    question = QuestionPublicModel.query.get(id)
    return render_template('question_detail.html', question=question)


@bp.route('question/public/detail/answer', methods=['POST'])
@login_required
def question_answer():
    form = AnswerQuestionForm(request.form)
    question_id = request.form.get('question_id')
    if form.validate():
        content = request.form.get('content')
        model = AnswerQuestionModel(content=content)

        user = g.get('user')
        model.author = user
        model.question_id = question_id

        print(f'question_id:{question_id}')

        db.session.add(model)
        db.session.commit()
        return redirect(url_for('qa.question_detail', id=question_id))
    else:
        flash('请输入评论内容')
        return redirect(url_for('qa.question_detail', id=question_id))


@bp.route('/search')
def search():
    # request.args.get('q')==> /search?q=xxx
    q = request.args.get('q')
    # query 使用模型字段名
    # query_by 直接字段名
    questions = QuestionPublicModel.query.filter(
        or_( # or_ 条件满足一个
            QuestionPublicModel.title.contains(q),
            QuestionPublicModel.content.contains(q)
        )).order_by(db.text('-create_time')).all()
    return render_template('index.html',questions=questions)
